package com.hoshiicloud.goods.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.goods.entity.goods.GoodsSpecificationsValues;
import com.hoshiicloud.goods.entity.goods.GoodsSpecificationsValuesType;
import com.hoshiicloud.goods.feign.IdGeneratorService;
import com.hoshiicloud.goods.mapper.goods.GoodsSpecificationsValuesMapper;
import com.hoshiicloud.goods.param.goods.GoodsSpecificationsValuesQueryParam;
import com.hoshiicloud.goods.service.GoodsSpecificationsValuesService;
import com.hoshiicloud.goods.service.GoodsSpecificationsValuesTypeService;
import com.hoshiicloud.goods.vo.GoodsSpecificationsValuesVo;
import java.time.LocalDateTime;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 商品规格_值 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-04
 */
@Slf4j
@Service
public class GoodsSpecificationsValuesServiceImpl extends
        ServiceImpl<GoodsSpecificationsValuesMapper, GoodsSpecificationsValues> implements
        GoodsSpecificationsValuesService {

    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private GoodsSpecificationsValuesMapper goodsSpecificationsValuesMapper;
    @Autowired
    private GoodsSpecificationsValuesTypeService goodsSpecificationsValuesTypeService;

    /**
     *
     */
    @Override
    @Logable(authName = "商品管理-商品规格_值管理-分页查询商品规格_值")
    @Cacheable(cacheNames = "GoodsSpecificationsValues", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public Page<GoodsSpecificationsValuesVo> getPage(Page<GoodsSpecificationsValuesVo> page,
            GoodsSpecificationsValuesQueryParam param, String key) {
        baseMapper.setPageByParam(page, param);
        return page;
    }


    /**
     * @param id
     * @return GoodsSpecificationsValues
     * @description: 根据id查询商品规格_值
     */
    @Override
    @Cacheable(cacheNames = "GoodsSpecificationsValues", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "商品管理-商品规格_值-查询商品规格_值 ")
    public GoodsSpecificationsValues getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * @param entity
     * @return boolean
     * @description: 新增商品规格_值
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsSpecificationsValues", allEntries = true)
    @Logable(authName = "商品管理-商品规格_值-新增商品规格_值")
    public boolean save(GoodsSpecificationsValues entity) {
        if (null != entity.getValueType()) {
            GoodsSpecificationsValuesType goodsSpecificationsValuesType = goodsSpecificationsValuesTypeService
                    .getById(entity.getValueType());
            if ("颜色".equals(goodsSpecificationsValuesType.getType()) && StringUtils.isBlank(entity.getValue())) {
                throw new ServiceException("色块不能为空");
            }
        }

        Integer maxOrdered = goodsSpecificationsValuesMapper.selectMaxOrdered(entity);
        if (null != maxOrdered) {
            maxOrdered += 1;
        } else {
            maxOrdered = 1;
        }

        // 主键ID生成
        String id = idGeneratorService.queryGeneratorId();
        if (StrUtil.isBlank(id)) {
            throw new ServiceException(CommonError.error("主键ID生成失败"));
        }

        // 新增数据
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        entity.setOrdered(maxOrdered.longValue());

        QueryWrapper<GoodsSpecificationsValues> q = new QueryWrapper<>();
        q.lambda()
                .eq(GoodsSpecificationsValues::getSpecId, entity.getSpecId())
                .eq(GoodsSpecificationsValues::getValueType, entity.getValueType())
                .eq(GoodsSpecificationsValues::getName, entity.getName())
                .eq(GoodsSpecificationsValues::getValue, entity.getValue())
                .eq(GoodsSpecificationsValues::getDeleted, 0);
        GoodsSpecificationsValues old = this.getOne(q);
        if (null != old) {
            throw new ServiceException("规格值已存在");
        }

        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改商品规格_值
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsSpecificationsValues", allEntries = true)
    @Logable(authName = "商品管理-商品规格_值管理-修改商品规格_值")
    public boolean updateById(GoodsSpecificationsValues entity) {
        GoodsSpecificationsValues oldE = this.getById(entity.getId());
        // 更新数据
        entity.setUpdatedTime(LocalDateTime.now());

        QueryWrapper<GoodsSpecificationsValues> q = new QueryWrapper<>();
        q.lambda()
                .eq(GoodsSpecificationsValues::getSpecId, oldE.getSpecId())
                .eq(GoodsSpecificationsValues::getValueType, entity.getValueType())
                .eq(GoodsSpecificationsValues::getName, entity.getName())
                .eq(GoodsSpecificationsValues::getValue, entity.getValue())
                .eq(GoodsSpecificationsValues::getDeleted, 0)
                .ne(GoodsSpecificationsValues::getId, entity.getId());
        GoodsSpecificationsValues old = this.getOne(q);
        if (null != old) {
            throw new ServiceException("规格值已存在");
        }

        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "GoodsSpecificationsValues", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+ ':specId('+ #root.args +')'")
    @Logable(authName = "商品管理-商品规格_值管理-根据商品specId查询规格值")
    public List<GoodsSpecificationsValues> getSpecificationsValueToNameListBySpecId(Long specId) {
        QueryWrapper<GoodsSpecificationsValues> goodsSpecificationsValuesQueryWrapper = new QueryWrapper<>();
        goodsSpecificationsValuesQueryWrapper.lambda()
                .eq(GoodsSpecificationsValues::getSpecId, specId)
                .select(GoodsSpecificationsValues::getName);
        return baseMapper.selectList(goodsSpecificationsValuesQueryWrapper);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsSpecificationsValues", allEntries = true)
    @Logable(authName = "商品管理-商品规格_值管理-删除商品规格_值")
    public boolean deleteById(Long id) {

        // 根据id查询数据
        GoodsSpecificationsValues entity = this.getById(id);
        if (entity == null) {
            log.error("删除商品规格_值异常，无法找到商品规格_值记录");
            throw new ServiceException("删除商品规格_值异常，无法找到商品规格_值记录");
        }

        //进行删除操作
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "GoodsSpecificationsValues", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-商品规格_值管理-根据id集合查询商品规格_值")
    public List<GoodsSpecificationsValues> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    @Override
    @Cacheable(cacheNames = "GoodsSpecificationsValues", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#specId")
    @Logable(authName = "商品管理-商品规格_值管理-根据规格id查询商品规格_值")
    public List<GoodsSpecificationsValues> getSpecById(Long specId) {
        if (specId == null) {
            throw new ServiceException("规格id为空,获取规格信息失败");
        }

        QueryWrapper<GoodsSpecificationsValues> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(GoodsSpecificationsValues::getId, specId)
                .eq(GoodsSpecificationsValues::getDeleted, 0);
        List<GoodsSpecificationsValues> specList = baseMapper.selectList(wrapper);

        if (specList.isEmpty()) {
            throw new ServiceException("获取规格信息失败,查询的规格值为空");
        }
        return specList;
    }


}
